

import 'package:todo_app/controllers/definitions/RtcRoomModel.dart';
import 'package:todo_app/thirdpart/flutter_fms/flutter_fms.dart';
import 'package:todo_app/utils/call/CallHelper.dart';
import 'package:todo_app/utils/call/contexts/IdleContext.dart';
import 'package:todo_app/utils/call/states/ConnectingState.dart';
import 'package:todo_app/utils/call/states/IdleState.dart';
import 'package:todo_app/utils/call/states/TalkState.dart';

class EndTransition extends ITransition {

  EndTransition({IdleState? idleState}) : super(toState: idleState);

  @override
  bool check() {
    if(toState == null || fromState == null) return false;
    final IdleState idleState = toState as IdleState;
    /// 强制关闭
    if(idleState.context?.force == true || idleState.context?.chatRoomId == null) return true;
    if(fromState is ConnectingState) {
      /// 对方超时未接听 需要提示用户
      if(
        idleState.context?.closeReason == CloseReason.ACCEPT_TIME_OUT ||
        idleState.context?.closeReason == CloseReason.REJECT
      ) {
        if(fromState is ConnectingState) {
          final RtcRoomModel? room = (fromState as ConnectingState).context?.room;
          if(room != null && room.created_by == room.user_id) {
            CallHelper.alertTimeout();
          } else {
            CallHelper.forceEndCall();
          }
        }
        return false;
      }
      /// 对方忙
      if(idleState.context?.closeReason == CloseReason.USER_BUSY) {
        CallHelper.alertUserBusy();
        return false;
      }
      /// 对方不在线
      if(idleState.context?.closeReason == CloseReason.USER_NOT_ONLINE) {
        CallHelper.alertUserNotOnline();
        return false;
      }
    }
    /// 链接中状态
    if(fromState is ConnectingState) {
      final ConnectingState connectingState = fromState as ConnectingState;
      if(connectingState.context?.requestSuccess != true) return true;
      if(connectingState.context?.requestSuccess == true && connectingState.context?.room.room_id == idleState.context?.chatRoomId){
        return true;
      }
    }
    /// 通话状态
    if(fromState is TalkState) {
      final TalkState talkState = fromState as TalkState;
      if(talkState.context?.room.room_id == idleState.context?.chatRoomId){
        return true;
      } 
    }
    return false;
  }

  @override
  bool onCompleteCallBack() {
    if(fromState is! IdleState) {
      final IdleState idleState = toState as IdleState;
      CallHelper.disconnectedFromState(idleState.context?.chatRoomId);
    }
    return false;
  }

  @override
  String get name => "EndTransition";
}